﻿package com.codingbros.fireworks.particles
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.display.Sprite;

	import flash.events.Event;

	import flash.geom.ColorTransform;
	import flash.geom.Point;
	
	public class ParticlesView extends Sprite
	{
		private const COLORS:Array = new Array(0x291e38, 0x6b3849, 0xd3643b, 0x2c9bc4);
		
		private var viewCenter:Point;
		private var viewWidth:int;
		private var viewHeight:int;
		
		private var numLines:int;

		private var lines:Array;
		private var linesContainer:Sprite;

		private const FADETRANSFORM:ColorTransform=new ColorTransform(1,1,1,0.99);
		private var renderBitmapData:BitmapData;
		private var renderBitmap:Bitmap;
		
		public function ParticlesView(center:Point, numLines:int = 30) 
		{
			viewCenter = center;
			
			viewWidth = viewCenter.x * 2;			
			viewHeight = viewCenter.y * 2;
			
			numLines = numLines;
			
			lines=new Array(numLines);

			linesContainer = new Sprite();

			renderBitmapData=new BitmapData(viewWidth,viewHeight,false,0x000000);
			renderBitmap=new Bitmap(renderBitmapData);
			addChild(renderBitmap);
			
			renderBitmap.smoothing = true;

			var colorNum:Number = 0;
			var line:ILineParticle;

			for (var i:int = 0; i < lines.length; i ++) {
				trace(COLORS.indexOf(colorNum));
				
				//line = new TechLineParticle();
				//line = new RandomLineParticle();
				//line = new OrbitLineParticle();
				line = new DrawLineParticles();
				line.init(COLORS[colorNum]);
				
				Shape(line).x = viewCenter.x;
				Shape(line).y = viewCenter.y;
				
				linesContainer.addChild(line as Shape);

				lines[i]=line;

				colorNum++;
				if (colorNum>=COLORS.length) {
					colorNum=0;
				}
			}

			this.addEventListener(Event.ENTER_FRAME, update);
		}
		
		
		private function update(e:Event):void 
		{
			updateLines();
			drawLines();
		}

		private function updateLines():void 
		{
			for (var i:int = 0; i < lines.length; i ++) 
			{
				lines[i].update();
			}
		}

		private function drawLines():void 
		{
			for (var i:int = 0; i < lines.length; i ++) 
			{
				lines[i].draw();
			}
			
			renderBitmapData.colorTransform(renderBitmapData.rect, FADETRANSFORM);
			renderBitmapData.draw(linesContainer);
		}		
	}	
}